from django.shortcuts import render
from django.views import View
from django import http
import re
from .models import User
from django.contrib.auth import login
from meiduo.utils.response_code import RETCODE

class RegisterView(View):
    # "注册"
# Create your views here.

    def get(self,request):
        ''' 提交注册页面'''
        return render(request, 'register.html')
    def post(self,request):
        '''注册逻辑'''
        query_dict = request.POST
        username = query_dict.get('username ')
        password = query_dict.get('password')
        password2 = query_dict.get('password2')
        mobile = query_dict.get('mobile')
        sms_code = query_dict.get('sms_code')
        allow = query_dict.get('allow ')

    #校验
        # if all(query_dict.dict().values())：

        #判断里面可迭代对象中的每个元素是否为None

        if all([username,password,password2,mobile,sms_code,allow]) is False:
            return http.HttpResponseForbidden('缺少参数')

        if not re.match(r'[a-zA-z0-9]{5,20}$',username):
            return http.HttpResponseForbidden('清输入5-20个字符的用户名')
        if not re.match (r'[a-zA-z0-9]{8,20}$',password):
            return http.HttpResponseForbidden('清输入8-20个字符的密码')
        if password != password2 :
            return  http.HttpResponseForbidden('俩次密码不一样')
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden('请输入正确的手机号码')
        # TODO：短信验证码




        #创建一个新用户：
        # user = User.objects.create(password=password)
        # user.set_password(password)
        # user.save()

        user =  User.objects.create_user(username=username)
        #状态保持，一般状态都是无状态（记录用户的登陆状态）
        login(request,user)
        #用户注册成功等于用户登陆
        return http.HttpResponse('注册成功，跳转界面')


class UsernameCountView(View):
#  判断用户的是否重复注册
    def get(self,request,username):
        #以username查询user模型，在取count,0:代表用户名没有重复，1：代表用户名重复
        count = User.objects.filter(username=username).count()
        #响应

        return http.JsonResponse({'code': RETCODE.OK,'errmsf':'ok','count' : count})


class MobileCountView(View):
    #  判断手机号的是否重复注册
    def get(self, request, mobile):
        # 以mobile查询user模型，在取count,0:代表用户名没有重复，1：代表用户名重复
        count = User.objects.filter(mobile=mobile).count()
        # 响应

        return http.JsonResponse({'code': RETCODE.OK, 'errmsf': 'ok', 'count': count})
